const express = require("express");
let createDBconnect = require("../db/createDBconnect.js");
const router = express.Router();

// 获取GDP数据的请求
router.get("/gdp",(req,res)=>{
    if(req.query?.city == null){
        return res.send({status: 202,message: "查询参数不正确"});
    }
    try{
        const connect = createDBconnect();
        let sqlString = `
        select * from gdp where \`地区\` = '${req.query.city}' union 
        select * from gdp_coverage where \`地区\` = '${req.query.city}' union
        select * from first_industry where \`地区\` = '${req.query.city}' union
        select * from second_industry where \`地区\` = '${req.query.city}' union
        select * from third_industry where \`地区\` = '${req.query.city}'
        `;

        connect.query(sqlString,(err,result)=>{
            if(err){
                console.log(`SQL error: ${err}!`);
                res.status(400);
            }
            else{
                let resultArr = [];
                let years = Object.keys(result[0]);
                // console.log(JSON.parse(JSON.stringify(result)));
                for(let i = 0;i<years.length;i++)
                {
                    let resultItem = {
                        year: years[i],
                        gdp: result[0][years[i]],
                        gdp_coverage: result[1][years[i]],
                        first_industry: result[2][years[i]],
                        second_industry: result[3][years[i]],
                        third_industry: result[4][years[i]],
                    }
                    resultArr.unshift(resultItem);
                }
                resultArr.pop();
                // console.log(resultArr);
                res.send({
                    status: 200,
                    data: resultArr,
                });
            }
        })


    }catch(err){

    }
});






module.exports = router;